package com.shopping.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shopping.bean.Goods;
import com.shopping.bean.Page;
import com.shopping.service.GoodsService;
import com.shopping.service.impl.GoodsServiceImpl;

/**
 * @author zjh
 *
 */
@WebServlet("/search.do")
public class SearchServlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String keyword = req.getParameter("keyword");
		if(keyword == null) {
			keyword = " ";
		}
		int pageNum;
		int pageSize;
		if(req.getParameter("pageNum") != null) {
			pageNum = Integer.parseInt(req.getParameter("pageNum"));
		}else {
			pageNum = 1;
		}
		if(req.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(req.getParameter("pageSize"));
		}else {
			pageSize = 15;
		}
		GoodsService bs = new GoodsServiceImpl();
		ObjectMapper om = new ObjectMapper();
		Page<Goods> page = bs.getGoods(keyword, pageNum, pageSize);
		resp.setCharacterEncoding("UTF-8"); //设置 后端给前端传回的编码格式为utf-8
		resp.setContentType("application/json");// 后端告知前端 返回的数据 是 json格式(不是html /css)
		resp.getWriter().print(om.writeValueAsString(page));

	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

}
